<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    width="80%"
    :minHeight="20"
    okText="提交"
    @register="register"
    :title="modalTitle"
    :loading="loading"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #slotUpload>
          <div class="clearfix">
            <a-upload
              accept="image/*"
              v-model:file-list="fileList"
              list-type="picture-card"
              :before-upload="beforeUpload"
              @preview="handlePreview"
            >
              <div v-if="fileList.length < 8">
                <plus-outlined />
                <div style="margin-top: 8px">Upload</div>
              </div>
            </a-upload>
            <a-modal
              :visible="previewVisible"
              :title="previewTitle"
              :footer="null"
              @cancel="handleCancel"
            >
              <img alt="example" style="width: 100%" :src="previewImage" />
            </a-modal>
          </div>
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, ref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Upload, Modal } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { getPopupContainer } from '/@/utils';
  import { cloneDeep } from 'lodash-es';
  import { getUrlProfix } from '/@/utils/index';
  import {
    getruntimeonlydriver,
    addequipment,
    updateequipment,
    uploadimg,
  } from '/@/api/equipmentLedger/index';
  // eslint-disable-next-line
  import { getdatalist, getdevicemodels } from '/@/api/equipmentModel/index';
  // eslint-disable-next-line
  import { getFactoryIdList } from '/@/api/enterprise/index';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
    // 设备类型
    deviceTypeList: {
      type: Array,
      default: () => [],
    },
    // 设备归属
    deviceOwnershipList: {
      type: Array,
      default: () => [],
    },
  });
  let loading = ref(false);
  const previewVisible = ref(false);
  const previewImage = ref('');
  const previewTitle = ref('');
  // 设备类型
  let deviceModelList = [];
  // 企业层级
  let levelObj = {
    1: 'GroupId', //集团
    2: 'CompanyId', //公司
    3: 'FactoryId', //工厂
    4: 'WorkshopId', //车间
    5: 'ProductionLineId', //产线
  };
  // 设备归属对象
  let deviceCategoryObj = {};
  // 型号对象
  let modalTitle = computed(() => {
    return `${props.info.type === 'add' ? '新建' : '编辑'}设备`;
  });
  const fileList = ref([]);
  const AUpload = Upload;
  const AModal = Modal;
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'Code',
      component: 'Input',
      label: '设备编码：',
      colProps: {
        span: 6,
      },
      componentProps: {
        disabled: false,
      },
      rules: [
        {
          required: true,
          message: '请输入设备编码',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Name',
      component: 'Input',
      label: '设备名称：',
      colProps: {
        span: 6,
      },
      rules: [
        {
          required: true,
          message: '请输入设备名称',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'ModelId',
      component: 'Select',
      label: '设备型号：',
      colProps: {
        span: 6,
      },
      componentProps: {
        getPopupContainer: () => getPopupContainer(),
        options: [],
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
      },
      rules: [
        {
          required: true,
          message: '请选择设备型号',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'TypeId',
      component: 'Select',
      label: '设备类型：',
      colProps: {
        span: 6,
      },
      componentProps: {
        getPopupContainer: () => getPopupContainer(),
        options: [],
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
        // eslint-disable-next-line
        onChange: (e) => {},
      },
      rules: [
        {
          required: true,
          message: '请选择设备类型',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Category',
      component: 'Select',
      label: '设备类别：',
      colProps: {
        span: 6,
      },
      componentProps: {
        getPopupContainer: () => getPopupContainer(),
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
        onChange: (e) => {
          // let tagretInfo = props.deviceTypeList.filter((item) => item.Id === e);
          // if (tagretInfo.length > 0) {
          //   getDeviceModels(tagretInfo[0].TypeName);
          // }
        },
      },
      rules: [
        {
          required: true,
          message: '请选择设备类别',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Manufacturer',
      component: 'Input',
      label: '生产厂商：',
      colProps: {
        span: 6,
      },
      componentProps: {},
    },
    {
      field: 'DriverId',
      component: 'TreeSelect',
      label: 'IoT设备编码：',
      colProps: {
        span: 6,
      },
      componentProps: {
        getPopupContainer: () => getPopupContainer(),
        treeDefaultExpandAll: true,
        placeholder: '请选择IoT设备编码',
        treeData: [],
        fieldNames: { children: 'Children', label: 'Name', value: 'Id' },
      },
    },

    {
      field: 'Ip',
      component: 'Input',
      label: '设备IP地址：',
      colProps: {
        span: 6,
      },
      componentProps: {},
    },
    {
      field: 'DutyOfficer',
      component: 'Input',
      label: '责任人：',
      colProps: {
        span: 6,
      },
      componentProps: {},
    },
    {
      field: 'MachineCode',
      component: 'Input',
      label: '机身编码：',
      colProps: {
        span: 6,
      },
    },
    {
      field: 'FactoryId',
      component: 'Select',
      label: '公司/工厂：',
      colProps: {
        span: 6,
      },
      componentProps: {
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
        getPopupContainer: () => getPopupContainer(),
        options: [],
        onChange: async (value) => {
          getWorkshop(value);
        },
      },
    },
    {
      field: 'WorkshopId',
      component: 'Select',
      label: '车间：',
      colProps: {
        span: 6,
      },
      componentProps: {
        fieldNames: { label: 'Name', value: 'Id', key: 'Id' },
        getPopupContainer: () => getPopupContainer(),
        options: [],
        onChange: (_e) => {},
      },
    },
    {
      field: 'DeviceLocation',
      component: 'Input',
      label: '设备位置：',
      colProps: {
        span: 6,
      },
    },
    {
      field: 'ProcessName',
      component: 'Input',
      label: '工序：',
      colProps: {
        span: 6,
      },
    },
    {
      field: 'UseStatus',
      component: 'Select',
      label: '使用状态：',
      colProps: {
        span: 6,
      },
      componentProps: {
        getPopupContainer: () => getPopupContainer(),
        placeholder: '请选择使用状态',
        options: [],
        fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
      },
    },
    {
      field: 'IsFictitious',
      component: 'RadioGroup',
      label: '是否虚拟设备：',
      colProps: {
        span: 6,
      },
      defaultValue: '0',
      componentProps: {
        options: [
          {
            label: '是',
            value: '1',
          },
          {
            label: '否',
            value: '0',
          },
        ],
      },
    },
    {
      field: 'uploadBox',
      component: 'Input',
      label: '设备图片：',
      slot: 'slotUpload',
      colProps: {
        span: 24,
      },
    },
  ];

  const [
    registerForm,
    { validateFields, setFieldsValue, resetFields, clearValidate, updateSchema, getFieldsValue },
  ] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 12,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['submitSuccess']);
  const [register] = useModal();

  const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
  };
  // 设备归属选择事件
  function handleCascaderChange(_e, selectedOptions) {
    if (_e && selectedOptions && _e.length > 0 && selectedOptions.length > 0) {
      selectedOptions.forEach((item) => {
        deviceCategoryObj[levelObj[item.Level]] = item.Key;
      });
    } else if (!_e && !selectedOptions) {
      deviceCategoryObj = {
        GroupId: '',
        CompanyId: '',
        FactoryId: '',
        WorkshopId: '',
        ProductionLineId: '',
      };
    }
  }
  async function getDeviceModels() {
    try {
      loading.value = true;

      let res = await getdevicemodels([
        {
          PageNO: 1,
          searchModel: '',
          searchModelName: '',
          searchTypeCategory: 0,
          PageSize: 1000,
        },
      ]);

      deviceModelList = res.Rows;
      updateSchema({
        field: 'ModelId',
        componentProps: {
          options: deviceModelList,
        },
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }
  const beforeUpload = async (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      createMessage.error('只能上传图片格式！');
      return Upload.LIST_IGNORE;
    }
    return false;
  };
  function getBase64(file: File) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  }
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = (await getBase64(file.originFileObj)) as string;
    }
    previewImage.value = file.url || file.preview;
    previewVisible.value = true;
    previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
  };
  async function handleSubmint() {
    try {
      let res = await validateFields();
      let imgUrl = getUrlProfix();
      // 过滤需要上传的图片
      let uploadList = fileList.value.filter((item) => !item.url);
      let resByUpload = await Promise.all(
        uploadList.map(async (item) => {
          let preview = (await getBase64(item.originFileObj)) as string;
          return uploadimg([preview]);
        }),
      );
      // 过滤已上传的图片
      let oldImgList = fileList.value
        .filter((item) => item.url)
        .map((item) => {
          let targetUrls = item.url.split(imgUrl);
          return targetUrls.length >= 1 ? targetUrls[1] : null;
        })
        .filter(Boolean);
      let params = {
        ...res,
        Images: [...resByUpload, ...oldImgList],
      };
      if (props.info.type === 'add') {
        await addequipment([params]);
      } else {
        await updateequipment([{ id: props.info.data.Id, ...params }]);
      }

      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', {});
    } catch (error: any) {
      console.log('not passing', error);
    }
  }
  // 设置可选项
  function setSelectable(arr) {
    arr.forEach((item) => {
      item.selectable = item.Type === 1;
      if (item.Children && item.Children.length > 0) {
        setSelectable(item.Children);
      }
    });
    return arr;
  }
  async function getEquipmentTree() {
    loading.value = true;
    try {
      let res = await getruntimeonlydriver();
      let treeData = setSelectable(Array.isArray(res) ? res : []);
      nextTick(() => {
        updateSchema({
          field: 'DriverId',
          componentProps: {
            treeData,
          },
        });
      });
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  }

  //获取使用状态
  async function getStatus() {
    try {
      let res = await getdatalist([
        {
          Code: 'equipment_status',
        },
      ]);
      updateSchema({
        field: 'UseStatus',
        componentProps: {
          options: res,
        },
      });
    } catch (error) {}
  }

  /**
   * 获取设备类别
   */
  async function getCategory() {
    let res = await getdatalist([
      {
        Code: 'equipment_category',
      },
    ]);
    updateSchema({
      field: 'Category',
      componentProps: {
        options: res,
      },
    });
  }

  /**
   * 获取车间
   * @param pid
   */
  async function getWorkshop(pid = '') {
    let res = await getFactoryIdList([['workshop'], pid]);
    updateSchema({
      field: 'WorkshopId',
      componentProps: {
        options: res,
      },
    });

    let fromData = await getFieldsValue();
    let WorkshopId = fromData.WorkshopId;
    let flag = true;
    for (let i = 0; i < res.length; i++) {
      let data = res[i];
      if (data.Id === WorkshopId) {
        flag = false;
      }
    }
    if (flag) {
      await setFieldsValue({ WorkshopId: null });
    }
  }

  /**
   *  获取设备归属
   */
  async function getDeviceCategory() {
    let res = await getFactoryIdList([['factory', 'company'], '']);
    updateSchema({
      field: 'FactoryId',
      componentProps: {
        options: res,
      },
    });
  }

  function handleVisibleChange(visible) {
    if (visible) {
      nextTick(async () => {
        updateSchema({
          field: 'TypeId',
          componentProps: {
            options: props.deviceTypeList,
          },
        });
        updateSchema({
          field: 'DeviceCategory',
          componentProps: {
            options: props.deviceOwnershipList,
          },
        });
        if (props.info.type !== 'add') {
          let setValue = cloneDeep(props.info.data);
          let {
            GroupId,
            CompanyId,
            FactoryId,
            WorkshopId,
            ProductionLineId,
            Images,
            typeId,
            DeviceCategory,
          } = setValue;
          setValue.type_name = typeId;
          // 赋值设备归属
          deviceCategoryObj = { GroupId, CompanyId, FactoryId, WorkshopId, ProductionLineId };
          // // 获取设备型号
          let tagretInfo = props.deviceTypeList.filter((item) => item.Id === typeId);
          console.log(`output->tagretInfo`, tagretInfo, typeId);
          // if (tagretInfo.length > 0) {
          //   await getDeviceModels(tagretInfo[0].TypeName);
          // }
          setValue.DeviceCategory = [
            GroupId,
            CompanyId,
            FactoryId,
            WorkshopId,
            ProductionLineId,
          ].filter(Boolean);
          // 设置图片列表
          if (Images && Images.length > 0) {
            fileList.value = Images.map((item) => {
              return {
                url: item,
              };
            });
          }
          setFieldsValue(setValue);
          updateSchema({
            field: 'code',
            componentProps: {
              disabled: true,
            },
          });
        }
        await getEquipmentTree();
        await getDeviceModels();
        await getCategory();
        await getStatus();
        await getDeviceCategory();
        await getWorkshop(props.info.data.FactoryId);
        clearValidate();
      });
    } else {
      deviceCategoryObj = {};
      fileList.value = [];
      updateSchema({
        field: 'code',
        componentProps: {
          disabled: false,
        },
      });
      resetFields();
    }
  }
</script>

<style lang="less" scoped>
  .slot-select {
    width: 100%;
    height: 32px;
    padding: 0 11px;
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
  }

  .slot-select:hover {
    border: 1px solid #1e80ff;
  }

  .slot-select-con {
    margin-right: 18px;
    line-height: 30px;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #000000d9;
    font-size: 14px;
  }

  .con-placeholder {
    color: #bfbfbf;
  }

  .icon-style {
    line-height: 30px;
    font-size: 11px;

    color: #bfbfbf;
  }

  .erro-style {
    border: 1px solid #ed6f6f !important;
  }

  .slot-select-diabled {
    background: #f5f5f5;
    cursor: not-allowed;

    .slot-select-con {
      color: rgba(0, 0, 0, 0.25);
    }
  }

  .slot-select-diabled:hover {
    border: 1px solid #d9d9d9;
  }
</style>
